package com.centit.util;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 用途：
 * Created by HEMIN
 * 创建日期： 2018-5-31.
 */
public class CommonDateUtil {
    /**
     * 计算两个日期之间相差的天数
     *
     * @param begin 较小的时间
     * @param end   较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date begin, Date end) {

        int days = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            begin = sdf.parse(sdf.format(begin));
            end = sdf.parse(sdf.format(end));
            Calendar cal = Calendar.getInstance();
            cal.setTime(begin);
            long time1 = cal.getTimeInMillis();
            cal.setTime(end);
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);
            days = Integer.parseInt(String.valueOf(between_days));

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
    //把一个字符串中的大写转为小写加_
    public static String exChange(String str){
        StringBuilder sb=new StringBuilder();
        char c;
        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                c = (char) (c + 32);
                sb.append("_"+c);
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }
    
    /**
         * 将短时间格式字符串转换为时间 yyyy-MM-dd 
     * 
      * @param strDate
      * @return
      */
   public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
     }
   
   /**
      * 获取现在时间
    * 
     * @return 返回短时间字符串格式yyyy-MM-dd
    */
 public static String getStringDateShort() {
   Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(currentTime);
   return dateString;
 }
}
